package ch.bfh.abhmcm.SoftwareEngineeringAndDesign.controller.database;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.swing.JOptionPane;

/**
 * @author Adrian Bronner
 */
public class DatabaseConnection {
	private static String SRV = "176.9.177.226";
	private static String DB = "db_cms";
	private static String USER = "cms";
	private static String PASSWORD = "cmsProject2012";

	private Connection connection = null;
	private boolean connected = false;

	/**
	 * @return true if the database connect was successful
	 */
	public boolean connect() {
		try {
			Class.forName("com.mysql.jdbc.Driver");
			// Class.forName("org.h2.Driver");
		} catch (ClassNotFoundException e) {
			System.out.println("error: MySQL JDBC driver missing.");
			e.printStackTrace();
		}
		try {
			connection = DriverManager.getConnection("jdbc:mysql://" + SRV
					+ "/" + DB, USER, PASSWORD);


		} catch (SQLException e) {
			System.out.println("error: MySQL JDBC connection failed.");
			JOptionPane.showMessageDialog(null,
					"Datenbanverbindung abgebrochen");
			e.printStackTrace();
			System.exit(0);
		}

		if (connection != null)
			connected = true;
		else
			connected = false;
		return connected;
	}

	/**
	 * @return false if the database disconnect was successful
	 */
	public boolean disconnect() {
		if (connected == false)
			return false;
		try {
			connection.close();
			connection = null;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		if (connection != null)
			connected = true;
		else
			connected = false;
		return connected;
	}

	/**
	 * @param query
	 *            a sql statement for the related database
	 * @return the result-set for the queried data
	 */
	public ResultSet query(String query) {
		if (connected == false)
			connect();
		ResultSet rs = null;
		try {
			Statement stmt = connection.createStatement();
			rs = stmt.executeQuery(query);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return rs;
	}

	/**
	 * 
	 * @param query
	 *            a SQL statement
	 * @return
	 */
	public void insertquery(String query) {

		if (connected == false)
			connect();

		try {

			Statement stmt = connection.createStatement();
			stmt.execute(query);
		} catch (SQLException e) {

			e.printStackTrace();
		}

	}


}